<template>
  <div class="scheduling">
    <div class="scheduling-nav">
      <!-- <TimeSwitch @timeSwitch="timeSwitchc" /> -->

      <SelectTimeZ @timeSwitch="timeSwitch" ></SelectTimeZ>
    </div>
    <div class="scheduling-search">
      <el-input v-model="formInline.empName" @blur="handlePageChange(1)" @change="handlePageChange(1)" style="width: 250px" placeholder="员工名称" class="scheduling-search-input" />
      <el-select placeholder="请选择科室" @change="handlePageChange(1)" clearable filterable style="width: 280px" v-model="formInline.deptId" class="scheduling-search-select">
          <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
      </el-select>
      <!-- <el-button type="primary"  class="scheduling-search-btn">查询</el-button> -->
      <div class="scheduling-search-right">
        <el-button type="primary" v-btnPermission="'btn-empSchedule-copy'" plain @click="copy"><el-icon style="margin-right: 5px; transform: rotate(180deg)">
            <CopyDocument />
          </el-icon>复制排班</el-button>
      
      </div>

    </div>
    <div class="scheduling-content">
      <el-table :data="tableData" class="table-components" :row-class-name="tableRowClassName" v-loading="loading"
        height="calc(100vh - 350px)" :cell-class-name="tableCellClassName" style="width: 100%">
        <el-table-column prop="empName" label="医生" align="center" fixed="left" width="140" />
        <el-table-column prop="deptName" label="科室" align="center" fixed="left" width="140" />
        <el-table-column prop="empNo" label="工号" align="center" fixed="left" width="140" />
        <el-table-column prop="address"  v-for="(value, index) in timeList"
          align="center" :key="value.date" width="182">
          <template #header>
            <!-- <span>{{new Date(value.times).getTime() == new Date(dayTime).getTime() ?  '今天':value.times + value.day}}</span> -->
            <span :style="isToday(value.times, value.day) ?'color: #16ADA4':''">{{isToday(value.times, value.day) ? '今天' : (value.times + value.day)}}</span>
          </template>
          <template #default="scope">
            <div style="width: 100%;height: 100%;position: relative;"  :class="scope.row.scheduleList[index].disabled ? 'table-cell-disabled' : ''">
            
              <div class="table-cell-content" v-if="scope.row.scheduleList[index].scheduleId">
                <div v-for="value in scope.row.scheduleList[index].detailList">
                  <div v-if="value.isLeave == 1">
                    {{ value.shiftName }} {{ value.roomName }}
                    <div style="color: #16ADA4;font-size: 12px;">请假：{{ value.leaveStartTime }} ~ {{ value.leaveEndTime }}
                    </div>
                  </div>
                  <div v-else>
                    {{ value.shiftName }} {{ value.roomName }}
                  </div>
                </div>
                <div class="table-cell-content-xf" v-if="!scope.row.scheduleList[index].disabled">
                  <el-button type="primary" v-btnPermission="'btn-empSchedule-updata'" @click="saveSchedule(scope.row, scope.row.scheduleList[index])"
                    class="scheduling-search-right"><el-icon style="margin-right: 5px;">
                      <Calendar />
                    </el-icon>排班</el-button>
                </div>
              </div>
              <div class="table-cell-content table-cell-content-null" v-else >
                <!-- <div style="color: #999">无排班</div> -->
                <div class="table-cell-content-xf" v-if="!scope.row.scheduleList[index].disabled">
                  <el-button type="primary" v-btnPermission="'btn-empSchedule-updata'" @click="saveSchedule(scope.row, scope.row.scheduleList[index])"
                    class="scheduling-search-right"><el-icon style="margin-right: 5px;">
                      <Calendar />
                    </el-icon>排班</el-button>
                </div>
              </div>

            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="scheduling-page-pagination">
      <Pagination style="margin-left: auto" :key="formInline.pageSize + 'Pagination' + formInline.pageNo" :count="total"
        :page-size="formInline.pageSize" :pageNo="formInline.pageNo" @onPagechange="handlePageChange"
        @onSizechange="handleSizeChange" />
    </div>
    <updata ref="updataRef" @closeDrawer="getEmpScheduleListData" />
    <updata2 ref="updataRef2" @closeDrawer="getEmpScheduleListData" />
  </div>
</template>
<script setup lang="ts">
import { CopyDocument, Calendar,Warning } from '@element-plus/icons-vue';
import { getWeekDates } from '@/utils/getWeekDates';
import { getEmpScheduleList } from '@/api/register/index';
import { deptGetSelectList } from '@/api/account'

import type { ScheduleDataResponseList, ScheduleList, SchedulingRole, ScheduleDataResponseForm } from '@/types/registrationSettings/index.ts';
import updata from './commons/updata.vue';
import updata2 from './commons/updata2.vue';

import dayjs from 'dayjs';
const dayTime = dayjs().format('YYYY-MM-DD');
const updataRef = ref<InstanceType<typeof updata>>();
const updataRef2 = ref<InstanceType<typeof updata2>>();

const dataType = ref(1); // 数据类型
const loading = ref<boolean>(false); // 数据类型
const isToday = (times:any, day:any) => {
  const startDate = formInline.value?.startDate;
  if (!startDate) return false;
  
  try {
    const dateStr = startDate.split('-')[0] +'-'+ times;
    const compareDate = new Date(dateStr);
    const today = new Date(dayTime);
    
    return compareDate.getTime() === today.getTime();
  } catch (error) {
    //console.warn('日期解析失败:', error);
    return false;
  }
};
const formInline = ref<ScheduleDataResponseForm>({
  startDate: '',
  endDate: '',
  pageNo: 1,
  pageSize: 10,
  empName: '',
  deptId: '',
});

const deptList = ref<any>([])
const getDeptGetSelectList = async () => {
  let res = await deptGetSelectList()
  if(res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  }
  deptList.value = res.data
}
getDeptGetSelectList()
const total = ref<number>(0);
const timeList = ref<any>([]);

const handlePageChange = (page: number) => {
  formInline.value.pageNo = page;
  //console.log('当前页码:', page);
getEmpScheduleListData()

};
const handleSizeChange = (size: number) => {
  formInline.value.pageNo = 1;

  formInline.value.pageSize = size;
  //console.log('每页条数:', size);
getEmpScheduleListData()

};
const tableRowClassName = () => {
  return 'no-hover-row';
};

const tableCellClassName = () => {
  return 'no-hover-cell';
};
const tableData = ref<ScheduleDataResponseList[]>([]);

const getEmpScheduleListData = async () => {
  loading.value = true
  
  const res = await getEmpScheduleList(formInline.value) as any;

  if (res.code !== '200') {
    //ElMessage.error(res.msg);
    return;
  }

  for (let index = 0; index < res.data.list.length; index++) {
    // 为每个员工创建一个排班列表
    // 这里假设每个员工的排班列表都需要包含当前时间范围
    let scheduleList = <any>[]
    for (let i = 0; i < timeList.value.length; i++) {


      let time = new Date(dayTime).getTime();
      let time2 = new Date(timeList.value[i].date).getTime();
      scheduleList.push({
        workDate: timeList.value[i].date,
        scheduleId: '',
        detailList: [],
        disabled: time > time2,
        day:time == time2 ? '今天' : ''
      });
    }
    let currentItem = res.data.list[index]
    if (currentItem.scheduleList.length) {
      for (let j = 0; j < scheduleList.length; j++) {
        for (let k = 0; k < currentItem.scheduleList.length; k++) {
          if (scheduleList[j].workDate === currentItem.scheduleList[k].workDate) {
            scheduleList[j].scheduleId = currentItem.scheduleList[k].scheduleId;
            scheduleList[j].detailList = currentItem.scheduleList[k].detailList;
          }
        }
      }
      currentItem.scheduleList = scheduleList;

    } else {
      currentItem.scheduleList = scheduleList;
    }
    currentItem.deptName = deptList.value.find((item:any) => item.deptId === currentItem.deptId)?.deptName || ''
  }
  tableData.value = res.data.list;
  total.value = res.data.totalCount;
  loading.value = false

  //console.log(res.list, '获取到的员工排班数据');
};


const saveSchedule = (row: SchedulingRole, value: ScheduleList) => {
  if (updataRef.value) {
    dataType.value = 0
    updataRef.value.open(row, value);
  }
};

const copy = () => {
  if (updataRef2.value) {
    updataRef2.value.open()
  }
}

const timeSwitchc = (val: string) => {
  formInline.value.startDate = val;

  //console.log(val);
  timeList.value = getWeekDates(6, val);
  formInline.value.endDate = timeList.value[6].date;

  //console.log('获取到的时间列表:', timeList.value);
  // getWeekDates(6,val)
  getEmpScheduleListData();

}

const timeSwitch = (val: any) => {
  //console.log(val,'时间切换');
  // formInline.value.startDate = val;
  formInline.value.startDate = dayjs(val.startDate).format('YYYY-MM-DD');
  formInline.value.endDate = dayjs(val.endDate).format('YYYY-MM-DD');
  timeList.value = getWeekDates(6, formInline.value.startDate)
  getEmpScheduleListData();

  // //console.log(val);
  // timeList.value = getWeekDates(6, val);
  // formInline.value.endDate = timeList.value[6].date;

  // //console.log('获取到的时间列表:', timeList.value);
  // // getWeekDates(6,val)
  // getEmpScheduleListData();
}

</script>
<style>
.el-table th.el-table__cell {
  background-color: #f8f9fa !important;
}
</style>
<style lang="scss" scoped> 
.scheduling {
  .scheduling-content .el-table td .cell {
    padding: 1px !important;
  }

  .scheduling-content .el-table td.el-table__cell {
    padding: 0 !important;
  }

  .scheduling-content .no-hover-row:hover td {
    background-color: initial !important;
  }

  .scheduling-content .no-hover-cell:hover {
    background-color: initial !important;
  }
  
  .table-cell-content {
    width: 100%;
    height: 110px;
    background: #ECF8F8;
    font-size: 12px;
    cursor: pointer;
    border-radius: 0px 0px 0px 0px;
    text-align: left;
    padding: 10px;

    div {
      // margin-bottom: 5px;
    }
  }

  .table-cell-content-null {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;
  }

  .table-cell-content:hover .table-cell-content-xf {
    display: flex;

  }

  .table-cell-content-xf {
    background-color: rgba(0, 0, 0, .5);
    display: none;
    align-items: center;
    justify-content: center;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
  }
  .table-cell-disabled .table-cell-content{
    background-color: #F3F3F3;
    opacity: 0.6;
  }
  .scheduling-nav {
    display: flex;
    justify-content: center;
    align-items: center;
    border-bottom: 1px solid #eaeaea;
    padding:0 0 12px 0;
  }

  .scheduling-search {
    display: flex;
    padding: 20px 24px;
    display: flex;
    align-items: center;

    .scheduling-search-input {
      margin-right: 20px;
    }

    .scheduling-search-select {
      margin-right: 20px;
    }

    .scheduling-search-right {
      margin-left: auto;
    }
  }

  .scheduling-page-pagination {
    display: flex;
    align-items: center;
    padding: 20px 24px;

    .drugStorage-page-pagination-total {
      margin-right: 20px;
    }
  }

  .scheduling-content {
    padding: 0px 24px 10px;

    .table-components {
      width: 100%;
    }
  }
}
</style>
